const vm = new Vue({
    el: 'main',
    data: {
        grade: {
            '描述相符': [0, 0, 0, 0, 0],
            '服务态度': [0, 0, 0, 0, 0],
            '环境卫生': [0, 0, 0, 0, 0],
            '交通位置': [0, 0, 0, 0, 0],
            '性价比': [0, 0, 0, 0, 0],
            '推荐指数': [0, 0, 0, 0, 0],
        },
        gradeName: {
            '描述相符': 'description_match_star',
            '服务态度': 'service_star',
            '环境卫生': 'environment_star',
            '交通位置': 'location_star',
            '性价比': 'cost_performance_star',
            '推荐指数': 'recommend_star',
        },
        comment: '',
        imgGroup: [],
        reqImgs: [],
        commentId: '',
    },
    methods: {
        getGrade,
    },
    mounted() {
        listenFile();
    },
});

function apiready() {
    fxj.fixLayout();
    !async function () {
        vm.commentId = await reqCommentId(fxj.getSearch().get('id'));
    }();
}

function getGrade(k, num) {
    vm.grade[k] = new Array(5).fill(0).map((n, i) => {
        if (i < num) return 1;
        return 0;
    });
}

function listenFile() {
    const ipt = document.getElementById('fileIpt');
    ipt.addEventListener('change', addImg);
}

async function addImg(evt) {
    const file = evt.target.files[0];
    upload(file);
    const urlData = await readFile(file);
    vm.imgGroup.push(urlData);
}

function triggerFileIpt() {
    const ipt = document.getElementById('fileIpt');
    triggerFileIpt = function () {
        ipt.click();
    };
    ipt.click();
}

function readFile(file) {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    return new Promise(resolve => {
        reader.onload = function (res) {
            resolve(res.target.result);
        };
    });
}

function checkAllInput() {
    for (let [k, list] of Object.entries(vm.grade)) {
        const ok = list.some(e => {
            return e > 0;
        });
        if (!ok) {
            mui.toast(`请为 ${k} 评分`);
            return false;
        }
    }
    if (!vm.comment) {
        mui.toast('请输入入住感言');
        return false;
    }
    return true;
}

function submit() {
    const ok = checkAllInput();
    const reqData = {};
    reqData.star = computeGrade();
    reqData.content = vm.comment;
    reqData.imgs = vm.reqImgs;
    reqData.orderId = fxj.getSearch().get('id');
    reqData.commentId = vm.commentId;
    console.log(reqData);
    ok && ajax({
        url: 'home/userComment/leaveMsg',
        data: reqData,
    }).then(
        res => {
            mui.toast(res.msg);
            if (res.err === 0) {
                fxj.closeWin();
            }
        },
    );
}

async function upload(file) {
    if (!file) return;
    const close = fxj.dialog.loading({
        des: '正在上传图片,请稍后',
    });
    const formData = new FormData();
    formData.append('img', file);
    formData.append('token', localStorage.getItem('token'));
    formData.append('commentId', vm.commentId);
    fetch(`${fxj.serverAddress}home/appUploadImg/upCommentImgs`, {
        method: 'POST',
        body: formData,
    }).then(
        res => res.json(),
    ).then(
        res => {
            close();
            mui.toast(res.msg);
            vm.reqImgs.push(res.data.imgId);
        },
    );

}

function computeGrade() {
    const grade = {};
    for (let [k, list] of Object.entries(vm.grade)) {
        let sum = 0;
        list.forEach(n => {
            (n > 0) && (sum += 1);
        });
        grade[vm.gradeName[k]] = sum;
    }
    return grade;
}

async function reqCommentId(orderId) {
    const res = await ajax({
        url: 'home/userComment/getCommentId',
        data: {
            orderId,
        },
    });
    return res.data;
}